package com.iot.core.manager.job;

import com.iot.core.util.MyDateTime;
import io.swagger.v3.oas.annotations.media.Schema;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.reflections.Reflections;

import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j
public class JobManager {

    private static   JobManager instance = null;
    //2.构造方法设为 private
    public JobManager() {
       instance=this;

    }
    public static JobManager getInstance() {

        return instance;
    }
    public void start() throws  Exception {
        var scheduler= StdSchedulerFactory.getDefaultScheduler();
        var startAt=new Date();
        startAt= MyDateTime.addSecond(startAt,5);//5秒后执行

        Class superClass=Class.forName("com.iot.core.manager.job.IMyJob");

        Reflections reflections = new Reflections("com.iot");
        Set<Class<?>> annotated = reflections.getSubTypesOf(superClass);
        for (Class<?> clazz : annotated) {
            var mjob=(IMyJob) clazz.getDeclaredConstructor().newInstance()  ;
            //2、任务实例（JobDetail）
            var jobDetail= JobBuilder.newJob((Class<? extends Job>) clazz) //加载任务类，与HelloJob完成绑定，要求HelloJob实现Job接口
                    .withIdentity(mjob.getJobName(),mjob.getJobGroup() ) //参数1：任务的名称（唯一实例）；参数2：任务组的名称
                    .build();
            //3、触发器（Trigger）
            var trigger= TriggerBuilder.newTrigger()
                    .withIdentity(mjob.getJobName(),mjob.getJobGroup()) //参数1：触发器的名称（唯一实例）；参数2：触发器组的名称
                    .startAt(startAt)
                    .withSchedule(  CronScheduleBuilder.cronSchedule(mjob.getCron() )   ) //每5秒执行一次
                    .build();
            //让调度器关联任务和触发器，保证按照触发器定义的条件执行任务
            scheduler.scheduleJob(jobDetail,trigger);
        }

        //启动
        scheduler.start();
    }

}
